package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.ReturnListDao;
import com.atguigu.jxc.dao.ReturnListGoodsDao;
import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.ReturnListGoodsService;
import com.atguigu.jxc.service.SupplierService;
import com.atguigu.jxc.util.AuthContextHolder;
import com.atguigu.jxc.vo.PurchaseListAndReturnListVo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReturnListGoodsServiceImpl implements ReturnListGoodsService {

    @Autowired
    private ReturnListGoodsDao returnListGoodsDao;

    @Autowired
    private ReturnListDao returnListDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private SupplierDao supplierDao;

    //退货单保存
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveReturnList(ReturnList returnList, String returnListGoodsStr, HttpSession session) {
        //获取用户信息
        User userInfo = AuthContextHolder.getUserInfo(session);
        //保存退货单
        returnList.setUserId(userInfo.getUserId());
        returnList.setTrueName(userInfo.getTrueName());
        returnListDao.saveReturnList(returnList);
        //根据supplierId查询供应商编号
        Supplier supplier =supplierDao.selectById(returnList.getSupplierId());
        //将string转为对象
        List<ReturnListGoods> returnListGoodsList = JSONObject.parseArray(returnListGoodsStr, ReturnListGoods.class);
        //遍历
        returnListGoodsList.forEach(item -> {
            //根据id拿到goods
            Goods goods =goodsDao.getGoodsById(item.getGoodsId());
            //判断是否为同一个供应商
            if (supplier.getSupplierName().equals(goods.getGoodsProducer())){
                item.setReturnListId(returnList.getReturnListId());
                //保存退货明细
                returnListGoodsDao.saveReturnListGoods(item);
                //退货单添加对应添加商品库存
                //退货数量不能大于库存数量
                if (goods.getInventoryQuantity()>=item.getGoodsNum()){
                    goods.setInventoryQuantity(goods.getInventoryQuantity()-item.getGoodsNum());
                    goodsDao.updateGoods(goods);
                }else {
                    throw new RuntimeException("销售数量不能大于库存数量");
                }
            }else {
                throw new RuntimeException("供货商不是同一个不能退货");
            }
        });
    }

    //退货单列表展示（可条件查询：单据号模糊、供应商、是否付款和日期区间）
    @Override
    public Map<String, Object> list(String returnNumber, Integer supplierId, Integer state, String sTime, String eTime) {
        //查询
        List<ReturnList> returnListList=returnListDao.listSelect(returnNumber,supplierId,state,sTime,eTime);
        Map<String, Object> map= new HashMap<>();
        map.put("rows",returnListList);
        return map;
    }

    //退货单商品信息 Integer returnListId
    @Override
    public Map<String, Object> goodsList(Integer returnListId) {
        //查询
        List<ReturnListGoods> returnListGoodsList=returnListGoodsDao.goodsList(returnListId);
        Map<String, Object> map= new HashMap<>();
        map.put("rows",returnListGoodsList);
        return map;
    }

    //删除退货单 Integer returnListId
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer returnListId) {
        if (returnListId!=null){
            //删除退货明细
            returnListGoodsDao.deleteReturnListGoods(returnListId);
            //删除退货单
            returnListDao.deleteReturnList(returnListId);
        }else{
            throw new RuntimeException();
        }
    }

    //修改供应商退货单退款状态 returnListId
    @Override
    public ServiceVO updateState(Integer returnListId) {
        try {
            //根据id查询退款状态
            ReturnList returnList =returnListDao.selectById(returnListId);
            //修改供应商退货单退款状态
            returnList.setState(1);
            returnListDao.updateState(returnList);
            return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new ServiceVO(ErrorCode.PARA_TYPE_ERROR_CODE,"修改退货单退款状态失败！");
        }
    }

    //退货统计（可根据 商品类别、商品编码或名称 条件查询）
    @Override
    public String count(String sTime, String eTime, Integer goodsTypeId, String codeOrName) {
        //  t_return_list_goods  t_return_list   t_supplier   t_goods_type
        List<PurchaseListAndReturnListVo> returnListVo=returnListDao.count(sTime,eTime,goodsTypeId,codeOrName);
        Gson gson = new Gson();
        //把list转为json
        String json = gson.toJson(returnListVo);
        return json;
    }
}
